package com.pingguopifa.domain;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


public class User implements UserDetails {

	private static final Logger LOGGER = Logger.getLogger(User.class);
	private static final long serialVersionUID = 4666854282363233772L;

	private String username;
	private String password;
	private String realname;
	private boolean enabled;
	
	private Set<UserRole> roles;
	
	public User() {
	}


	public User(String userName) {
		super();
		this.username = userName;
	}
	
	public Set<UserRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<UserRole> roles) {
		this.roles = roles;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Override
	public String getUsername() {
		return username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return enabled;
	}

	public String getRealname() {
		return realname;
	}

	public void setRealname(String realname) {
		this.realname = realname;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
		 Object[] res = roles.toArray();
		for (int i = 0; i < res.length; i++) {
			String roleName = ((UserRole)res[i]).toString();
			LOGGER.debug("userName: " + getUsername() + " || userRole: " + roleName);
			SimpleGrantedAuthority role = new SimpleGrantedAuthority(roleName);
			grantedAuthorities.add(role);
		}
		return grantedAuthorities;
	}

}
